package com.sixbing.spider.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sixbing.spider.bean.User;
import com.sixbing.spider.service.IUserService;
import com.sixbing.spider.utils.ResponseUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @RequestMapping("/showUser.do")
    public void selectUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String strId = request.getParameter("id");
        if (StringUtils.isEmpty(strId)) {
            ResponseUtils.ResponseError(response, 400, "id is null");
            return;
        } else {
            try {
                long userId = Long.parseLong(strId);
                User user = this.userService.selectUser(userId);
                ResponseUtils.Response(response, user);
            } catch (Exception e) {
                ResponseUtils.ResponseError(response, 404, "服务器内部错误");
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/showUserList.do")
    @ResponseBody
    public void selectUserList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String startPage = request.getParameter("page");
        String PageSize = request.getParameter("PageSize");
        if (StringUtils.isEmpty(username)) {
            ResponseUtils.ResponseError(response, 400, "id 为空");
            return;
        } else {
            try {
                PageHelper.startPage(1, 3);
                List<User> users = this.userService.selectUserList(username);
                PageInfo<User> pi = new PageInfo<>(users);
                ResponseUtils.Response(response, pi);
            } catch (Exception e) {
                ResponseUtils.ResponseError(response, 404, "服务器内部错误");
                e.printStackTrace();

            }
        }

    }
}
